package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.PageResult;
import com.heima.mapper.VmTypeMapper;
import com.heima.pojo.VmType;
import com.heima.pojo.dto.VmTypeDto;
import com.heima.service.VmTypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class VmTypeServiceImpl extends ServiceImpl<VmTypeMapper, VmType> implements VmTypeService {

    private final VmTypeMapper vmTypeMapper;

    /**
     * 分页查询机器类型
     * @param dto
     * @return
     */
    @Override
    public PageResult<VmType> searchVmType(VmTypeDto dto) {
        LambdaQueryWrapper<VmType> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(dto.getName() != null && dto.getName().length() > 0, VmType::getName, dto.getName());

        Page<VmType> page = new Page<>(dto.getPageIndex(), dto.getPageSize());
        Page<VmType> result = page(page, wrapper);

        return new PageResult<>(
                dto.getPageIndex(),
                dto.getPageSize(),
                (int) result.getPages(),
                result.getTotal(),
                result.getRecords()
        );
    }

    /**
     * 保存机器类型
     * @param vmType
     * @return
     */
    @Override
    public Boolean saveVmType(VmType vmType) {
        return super.save(vmType);
    }

    /**
     * 修改机器类型信息
     * @param vmType
     * @return
     */
    @Override
    public Boolean updateVmType(VmType vmType) {
        return vmTypeMapper.updateById(vmType) > 0;
    }

    @Override
    public Boolean removeVmType(Integer id) {
        // 如果有机器在使用，则不能删除
        if (vmTypeMapper.queryVmCount(id) > 0) {
            return false;
        }
        return vmTypeMapper.deleteById(id) > 0;
    }
}
